<template>
  <div>
    <!--上传图片接口  -->
    <el-upload
      :action=" `${this.$basePath}?service=App.MaskMachines.UploadFile&api=193`"
      list-type="picture-card"
      :data="dataparms"
      :on-remove="handleRemove"
      :on-preview="handlePictureCardPreview"
      :limit="9"
      :multiple="isMultiple"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :on-exceed="handleExceed"
      :on-error="imgUploadError"
      :file-list="productImgs"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
export default {
  computed: {
    ...mapState({
      token: state => state.Authorization
    })
  },
  data() {
    return {
      isMultiple: true,
      productImgs: [],
      dialogImageUrl: "",
      dialogVisible: false,
      dataparms: {},
      imgUrl: []
    };
  },
  mounted() {
    //传文件带的参数
    this.dataparms = {
      token: this.token,
      type: "image"
    };
  },
  methods: {
    handleRemove(fileList) {
      this.imgUrl.splice(this.imgUrl.indexOf(fileList.response.data.path), 1);
      console.log("移除");
      console.log(this.imgUrl);
    },
    handlePictureCardPreview(file) {
      console.log("预览图片");
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    beforeAvatarUpload(file) {
      //文件上传之前调用做一些拦截限制
      console.log("上传前做限制", file);
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图片只能是 JPG 格式或PNG格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
        return false;
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res, file) {
      //图片上传成功
      console.log("上传成功");
      console.log(res);
      if (res.ret == 200) {
        this.imgUrl.push(res.data.path);
      }
      console.log("图片数组：", this.imgUrl);
    },
    handleExceed(files, fileList) {
      //图片上传超过数量限制
      this.$message.error("上传图片不能超过9张!");
      console.log(file, fileList);
    },
    imgUploadError(err, file, fileList) {
      //图片上传失败调用
      console.log(err);
      this.$message.error("上传图片失败!");
    }
  }
};
</script>
<style lang="less" scoped>
/deep/.el-upload--picture-card{
      width: 80px;
    height: 80px;
    line-height: 80px;
    background: transparent;
}
/deep/.el-upload-list--picture-card .el-upload-list__item{
     width: 80px;
    height: 80px;
    line-height: 80px;
}
/deep/.el-upload-list--picture-card .el-upload-list__item .el-icon-check, .el-upload-list--picture-card .el-upload-list__item .el-icon-circle-check{
    position: absolute;
    top: 0;
    left: 14px;
}
</style>
